package com.woniu.servicepay.controller;

import com.woniu.servicepay.service.AlipayService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Synchronized;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/alipay")
@Log4j2
public class AlipayController {
    @Autowired
    private AlipayService alipayService;

//    public UniProductOrderController(SimpMessagingTemplate messagingTemplate) {
//        this.messagingTemplate = messagingTemplate;
//    }

//    @Autowired
//    RedissonClient redissonClient;

    /**
     * 测试
     */
    @GetMapping("/test")
    public String test() {
        return "测试成功！";
    }

    /**
     *  支付
     * @param params 订单信息
     * @return
     */
    @PostMapping("/pay")
    @Synchronized
    public Map<String, Object> pay(@RequestBody Map<String, String> params) {
        log.info("收到支付请求，参数：" + params);

        // 参数校验
        String orderId = params.get("orderId");
        String amount = params.get("amount");
        String productName = params.getOrDefault("productName", "默认商品");

        if (orderId == null || amount == null) {
            throw new IllegalArgumentException("缺少必要参数");
        }
        //key用OrderId，确保同一订单串行化
//        RLock paylock = redissonClient.getLock("pay:lock:" + orderId);
        try {
            //加锁
//            paylock.lock();
            // 调用支付宝服务
            String orderPayUrl = alipayService.appPay(
                    productName,
                    orderId,
                    new BigDecimal(amount).toString()
            );

            // 返回uniapp需要的结构
            Map<String, Object> response = new HashMap<>();
            response.put("statusCode", 200);
            response.put("msg", "success");
            response.put("data", orderPayUrl); // 支付宝原始订单信息

            return response;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("支付处理失败");
        }
    }
    /**
     * 订单回调
     *
     * @return
     */
    @PostMapping("/notify")
    @Synchronized
    public String orderNotify(HttpServletRequest request) {
        //调用service
        return alipayService.orderNotify(request);
    }
//    private final SimpMessagingTemplate messagingTemplate;
}
